package com.example;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * Created with IntelliJ IDEA.
 * ClassName: Word
 * Package: com.example
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-07-28
 * Time: 14:33
 */

public class Word {
    public static void main(String[] args) throws Exception {
        //统计单词的个数
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        SingleOutputStreamOperator<Tuple2<String, Integer>> map = env
                .socketTextStream("hadoop102", 7777)
                .flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
                    @Override
                    public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                        //一行可能有多个单词 通过空格切分之后
                        String[] s = value.split(" ");
                        //循环遍历发往下游 不用直接return
                        for (String word : s) {
                            out.collect(Tuple2.of(word,1));
                        }
                    }
                });

        //聚合 计算 之前要 keyBy
        //根据单词来keyBy
        map.keyBy(value -> value.f0)
                .sum(1).print();


        env.execute();

    }
}
